import escapeHtml from "escape-html";
import config from "./config";
//@ts-ignore
import fetchajaxgettext from "./fetchajaxgettext.cjs";
import { getlinkhrefmd } from "./getlinkhrefmd";
import { getlinkmdandid } from "./getlinkmdandid";
import { guid } from "./guid";
import { handleextralink } from "./handleextralink";
import { htmltoelement } from "./htmltoelement";
import { mdpageloader } from "./mdpageloader";
import { StateType } from "./StateType";
//@ts-ignore
import { urlclearhashandsearch } from "./urlclearhashandsearch";

export function handleneedtitle(
    tmpcontainer: HTMLDivElement,
    // path: string,
    title: string
) {
    const firsttag = tmpcontainer.firstElementChild?.tagName?.toLowerCase?.();
    const needtitle = Boolean(
        firsttag && !["h1", "h2", "h3", "h4", "h5", "h6"].includes(firsttag)
    );
    // const title = cachetitle.get(path);
    if (needtitle && title) {
        tmpcontainer.insertAdjacentHTML(
            "afterbegin",
            `<h1 id='top'>${escapeHtml(title)}</h1>`
        );
    }
}

export function headeraddanchor(tmpcontainer: HTMLElement, path: string) {
    const headerselectors = ["h1", "h2", "h3", "h4", "h5", "h6"];

    const headereles = headerselectors
        .map((t) => Array.from(tmpcontainer.querySelectorAll(t)))
        .flat() as HTMLElement[];
    headereles.forEach((e) => {
        // console.log(router.getparams());
        // console.log(e);
        const id = e.id;
        const href = getlinkmdandid(path, id);

        var oldhtml = e.textContent || "";
        const anchor = htmltoelement(
            `<a class='anchor scrollIntoView' href=${href}><span class='anchor-icon'></span>${escapeHtml(
                oldhtml
            )}</a>`
        );
        anchor.classList.add("navigate");
        e.innerHTML = "";
        e.appendChild(anchor);
        // );
    });
}
export function addsubheaders(
    // states: StateType,
    tmpcontainer: HTMLElement,
    path: string
): string {
    // const { cachetoc } = states;
    // if (cachetoc.get(path)) {
    //     return;
    // }
    const headerselectors = ["h1", "h2", "h3", "h4", "h5", "h6"];

    const headereles: HTMLElement[] = Array.from(
        tmpcontainer.querySelectorAll("*")
    ).filter((e) =>
        headerselectors.includes(e.tagName.toLowerCase())
    ) as HTMLElement[];
    const subheaders = headereles.map((e) => {
        // console.log(router.getparams());
        // console.log(e);
        const id = e.id;
        const href = getlinkmdandid(path, id);

        const tag = e.tagName.toLowerCase();
        const text = e.textContent || "";
        return { tag, text, href };
    });
    // console.log(subheaders);
    if (subheaders.length === 0) {
        return "";
    }
    const subheaderhtml =
        `<ul style="padding-left: 0px;">` +
        subheaders
            .map((o) => {
                const { href, tag, text } = o;

                const anchor = htmltoelement(
                    `<a href="${href}" class="sidebar-sub-header ">${escapeHtml(
                        text
                    )}</a>`
                );
                anchor.classList.add("navigate");
                anchor.classList.add(
                    "mybutton-8731e6c5bb5148e49e14cca7cdfa73e8"
                );
                anchor.classList.add("sidebar-link-item");
                return `
            <li><div class="subheader-${tag}">${anchor.outerHTML} </div></li>`;
            })
            .join("") +
        `</ul>`;
    // console.log(subheaderhtml);
    // cachetoc.get(path) || cachetoc.set(path, subheaderhtml);
    // console.log(cachetoc);
    return subheaderhtml;
}

export function changelinkmd(
    menulist: string[],
    tmpcontainer: HTMLElement,
    path: string
) {
    const links: HTMLAnchorElement[] = Array.from(
        tmpcontainer.querySelectorAll("a")
    );
    links.forEach((a) => {
        var ahref = a.href;
        var realmdpath = String(new URL(ahref, path));
        let tmppath = urlclearhashandsearch(realmdpath);

        if (
            ahref &&
            ahref?.endsWith(".md") &&
            new URL(tmppath).pathname.endsWith(".md") &&
            menulist.includes(tmppath)
        ) {
            setpagelink(a, tmppath);
            return;
        } else {
            handleextralink(a);
            return;
        }
    });
}
function setpagelink(a: HTMLAnchorElement, tmppath: string) {
    a.href = getlinkhrefmd(tmppath);
    a.classList.add(
        ..."mui-btn mui-btn-primary mui-btn-outlined mybutton-8731e6c5bb5148e49e14cca7cdfa73e8".split(
            " "
        )
    );
    a.classList.add("navigate");
}

// export function resolvetitlesave(
//     states: StateType,
//     tmpcontainer: HTMLElement,
//     path: string
// ) {
//     const { cachetitle } = states;
//     let mdtitle = (() => {
//         let selectors = ["h1", "h2", "h3", "h4", "h5", "h6"];
//         for (let sel of selectors) {
//             //@ts-ignore
//             let title = tmpcontainer.querySelector(sel)?.textContent || "";
//             if (title) {
//                 return title;
//             }
//         }
//         return;
//     })();

//     if (mdtitle && !cachetitle.get(path)) {
//         cachetitle.set(path, mdtitle);
//     }
// }

export function handlecodecopy(tmpcontainer: HTMLElement) {
    Array.from(tmpcontainer.querySelectorAll("pre")).forEach((e) => {
        e.classList.add("position-relative");
    });
    Array.from(tmpcontainer.querySelectorAll("pre>code")).forEach((e) => {
        const codecontenguid = "clip-" + guid();

        e.setAttribute("id", codecontenguid);

        e.insertAdjacentHTML(
            "afterend",
            `<button class="btn btn-outline-primary mybutton-8731e6c5bb5148e49e14cca7cdfa73e8 clipbutton position-absolute right-0 top-0" data-clipboard-target="#${codecontenguid}"><span class="clipboard-icon"></span></button>`
        );
    });
}
// const rendermarkdownpage = async function (
//     mdurl: string,
//     baseurl: string,
//     rawmd: string,
//     menulist: string[],
//     cachetitle: Map<string, string>
// ): Promise<StateType> {
//     const states = createstate();
//     const data = rawmd;
//     console.log([data]);
//     const path = mdurl;
//     const { cachemain } = states;

//     return states;
// };
export async function commonloadpage(states: StateType, path: string) {
    const rawmd: string = await fetchajaxgettext(path);
    const { baseurl } = config;
    const { cachetitle, menulist } = states;
    console.log([rawmd]);
    const title = cachetitle.get(path);
    if (!title) {
        throw new Error("title not found");
    }
    const { toc, main, stylecssrules /* , dependencies  */ } =
        await mdpageloader(path, rawmd, baseurl, title, Array.from(menulist));

    states.cachetoc.get(path) || states.cachetoc.set(path, toc);
    states.cachemain.get(path) || states.cachemain.set(path, main);
    states.cachestylecssrules.get(path) ||
        states.cachestylecssrules.set(path, stylecssrules);
    /*     states.cachedependencies.get(path) ||
        states.cachedependencies.set(path, dependencies); */
}
